package com.wing.chanjet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wing.chanjet.entity.TopicMessage;
import com.wing.redis.utils.redis.RedisHelperImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 畅捷通消息订阅回调
 *
 * @author xiayang
 */
@Validated
@RestController("chanjetController")
@RequestMapping("chanjet/admin/chanjet")
@Slf4j
public class ChanjetController {

    @Resource
    private RedisHelperImpl redisHelper;

    /**
     * 畅捷通消息订阅回调
     *
     * @return
     */
    @PostMapping("/topicCallback")
    public String topicCallback(@RequestBody String message, HttpServletRequest request) {
        log.info("消息订阅回调开始");
        //消息密钥
        /*String key = "2f58e46e8579026b";*/
        // 获取请求域名
        String domain = (String) request.getAttribute("currentDomain");
        log.info("消息订阅回调获取key00000域名---"+domain);
        Object redisHelperValue = redisHelper.getValue(domain + "-appMsgSecret-");
        String key ="";
        if(redisHelperValue!=null){
            key=redisHelperValue.toString();
        }
        log.info("消息订阅回调获取key111111---"+key);
        if(StringUtils.isBlank(key)){
            key="2f58e46e8579026b";
        }

        log.info("消息订阅回调获取key2222222---"+key);
        //返回内容-加密
        Map<String, String> map = JSONObject.parseObject(message, Map.class);
        message = map.get("encryptMsg");
        log.info("message-----------info---------------",message);
        try {
            //解密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
            byte[] bytes = Base64.decodeBase64(message);
            bytes = cipher.doFinal(bytes);
            String resultObj = new String(bytes, StandardCharsets.UTF_8);
            TopicMessage topicMessage = JSONObject.parseObject(resultObj, TopicMessage.class);
            log.info("begin print call back info topicMessage:{}", JSONObject.parseObject(resultObj, TopicMessage.class));
            System.out.println("ID: "+topicMessage.getId());
            System.out.println("appKey: "+topicMessage.getAppKey());
            System.out.println("msgType: "+topicMessage.getMsgType());
            System.out.println("time: "+topicMessage.getTime());
            System.out.println("appTicket: "+topicMessage.getBizContent().getAppTicket());
            //写入redis缓存
            redisHelper.valuePut("appTicket", topicMessage.getBizContent().getAppTicket());
            //从redis缓存取出
            System.out.println("redis-appTicket: "+redisHelper.getValue("appTicket"));
            log.info("end print call back info topicMessage:{}", JSONObject.parseObject(resultObj, TopicMessage.class));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        Map result = new HashMap();
        result.put("result", "success");
        log.info("消息订阅回调结束");
        return JSON.toJSONString(result);
    }

    public static void main(String[] args) {
        String message = "{\"encryptMsg\":\"C9BLyo3P7JTc7PghCKhb5Z5jfTWYYQJnwDgSVO7xog9HWQJjEq6cdhg6xxIsrXKzu8bjrU8FX8hD2DDPILJkPO+WmOQncsQgftOCXV9VMH80grLqgHwt34gk3sq4Kl/x27ajqcq3Zqhn/Ur3hUYCd9WgodoVKVmSGxDrgSjK5enMqOVEfWVCTFvi/HaDPAgqTmMY+eDTQ+hzyCYW5TSZWLPwQwR811PBp9AmC2wOxvINklzahCASF7PI8nhTAxqnd9vHqUWBvFNx17fBE9nrgMvD0pM9v9yAGiXQ1Vq/wNGkp6ZFCSJm7qoBGQu5ME0kzRYmBdAVmgvkItttO0Ir6A==\"}";
        Map<String, String> map = JSONObject.parseObject(message, Map.class);
        System.out.println(map.get("encryptMsg"));

        String resultString = "{\"id\":\"6c0bc444-f4f4-236f-5281-6453b76f01d1\",\"appKey\":\"HARlwiwZ\",\"appId\":\"\",\"msgType\":\"APP_TICKET\",\"time\":\"1736220645287\",\"bizContent\":{\"appTicket\":\"t-4473851d918c4737ac2b1b92b3f32ee3\"},\"orgId\":\"\",\"bookCode\":\"\",\"requestId\":\"\",\"uniqueId\":\"\"}\n";
        TopicMessage topicMessage = JSONObject.parseObject(resultString, TopicMessage.class);
        System.out.println("ID: "+topicMessage.getId());
        System.out.println("appKey: "+topicMessage.getAppKey());
        System.out.println("appId: "+topicMessage.getAppId());
        System.out.println("msgType: "+topicMessage.getMsgType());
        System.out.println("time: "+topicMessage.getTime());
        System.out.println("orgId: "+topicMessage.getOrgId());
        System.out.println("bookCode: "+topicMessage.getBookCode());
        System.out.println("requestId: "+topicMessage.getRequestId());
        System.out.println("uniqueId: "+topicMessage.getUniqueId());
        System.out.println("appTicket: "+topicMessage.getBizContent().getAppTicket());
    }
}
